package com.kakarote.admin.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.kakarote.admin.common.AdminCodeEnum;
import com.kakarote.admin.common.AdminConst;
import com.kakarote.admin.common.AdminModuleEnum;
import com.kakarote.admin.entity.BO.*;
import com.kakarote.admin.entity.PO.AdminConfig;
import com.kakarote.admin.entity.PO.AdminUserConfig;
import com.kakarote.admin.entity.VO.CloudConfigVO;
import com.kakarote.admin.entity.VO.ModuleSettingVO;
import com.kakarote.admin.service.IAdminConfigService;
import com.kakarote.admin.service.IAdminUserConfigService;
import com.kakarote.admin.service.IAdminUserService;
import com.kakarote.common.log.annotation.OperateLog;
import com.kakarote.common.log.entity.OperationLog;
import com.kakarote.common.log.entity.OperationResult;
import com.kakarote.common.log.enums.ApplyEnum;
import com.kakarote.common.log.enums.BehaviorEnum;
import com.kakarote.common.log.enums.OperateObjectEnum;
import com.kakarote.common.log.enums.OperateTypeEnum;
import com.kakarote.core.common.ApiExplain;
import com.kakarote.core.common.Const;
import com.kakarote.core.common.Result;
import com.kakarote.core.entity.BasePage;
import com.kakarote.core.entity.PageEntity;
import com.kakarote.core.feign.crm.entity.SimpleCrmEntity;
import com.kakarote.core.servlet.ApplicationContextHolder;
import com.kakarote.core.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 客户规则 前端控制器
 * </p>
 *
 * @author zhangzhiwei
 * @since 2020-04-27
 */
@RestController
@RequestMapping("/adminConfig")
@Api(tags = "系统配置接口")
public class AdminConfigController {

    @Autowired
    private IAdminConfigService adminConfigService;

    @Autowired
    private IAdminUserConfigService adminUserConfigService;


    @ApiModelProperty(value = "设置金额单位")
    @PostMapping("/setMonetaryUnit")
    @OperateLog(apply = ApplyEnum.SYSTEM_SETTING, behavior = BehaviorEnum.UPDATE, object = OperateObjectEnum.AMOUNT_UNIT, type = OperateTypeEnum.SETTING)
    public Result setMonetaryUnit(@RequestBody @ApiParam("金额单位") List<MonetaryUnitBO> monetaryUnit) {
        List<OperationLog> operationLogList = adminConfigService.setMonetaryUnit(monetaryUnit);
        return OperationResult.ok(operationLogList);
    }

    @ApiModelProperty(value = "获取设置金额单位")
    @PostMapping("/getMonetaryUnit")
    public Result<List<MonetaryUnitBO>> getMonetaryUnit() {
        AdminConfig monetaryUnit = adminConfigService.lambdaQuery().eq(AdminConfig::getName, "monetaryUnit").one();
        if (ObjectUtil.isNotEmpty(monetaryUnit)) {
            String unitValue = monetaryUnit.getValue();
            return Result.ok(JSON.parseArray(unitValue, MonetaryUnitBO.class));
        }
        return Result.ok(new ArrayList<>());
    }

    /**
     * 设置系统配置
     */
    @ApiOperation(value = "设置企业配置")
    @PostMapping("/setAdminConfig")
    @OperateLog(apply = ApplyEnum.SYSTEM_SETTING, behavior = BehaviorEnum.UPDATE, object = OperateObjectEnum.COMPANY, type = OperateTypeEnum.SETTING)
    public Result setAdminConfig(@RequestBody AdminCompanyBO adminCompanyBO) {
        OperationLog operationLog = adminConfigService.setAdminConfig(adminCompanyBO);
        return OperationResult.ok(ListUtil.toList(operationLog));
    }

    /**
     * 查询企业配置
     *
     * @return Result
     * @author zhangzhiwei
     */
    @ApiOperation(value = "查询企业配置")
    @PostMapping("/queryAdminConfig")
    public Result<AdminCompanyBO> queryAdminConfig() {
        return Result.ok(adminConfigService.queryAdminConfig());
    }

    @ApiOperation(value = "忽略过期提醒消息")
    @PostMapping("/ignoreCompanyStatus")
    public Result ignoreCompanyStatus() {
        adminConfigService.ignoreCompanyStatus();
        return Result.ok();
    }

    /**
     * 查询企业配置
     *
     * @return Result
     * @author zhangzhiwei
     */
    @ApiOperation(value = "查询企业配置")
    @PostMapping("/queryCloudConfig")
    public Result<CloudConfigVO> queryCloudConfig() {
        long count = ApplicationContextHolder.getBean(IAdminUserService.class).count();
        CloudConfigVO configVO = new CloudConfigVO();
        configVO.setAllNum(999);
        configVO.setUsingNum(count);
        configVO.setEndTime("2099-12-31 23:59:59");
        return Result.ok(configVO);
    }

    /**
     * 查询企业模块配置
     *
     * @author zhangzhiwei
     */
    @ApiOperation(value = "查询企业模块配置")
    @PostMapping("/queryModuleSetting")
    public Result<List<ModuleSettingVO>> queryModuleSetting() {
        return Result.ok(adminConfigService.queryModuleSetting());
    }


    @ApiOperation(value = "查询增值服务模块的状态")
    @PostMapping("/queryModuleApply")
    public Result<List<ModuleSettingVO>> queryModuleApply(@RequestBody AdminQueryModuleApplyBO queryBO) {
        return Result.ok(adminConfigService.queryModuleApply(queryBO));
    }

    /**
     * 设置企业模块
     *
     * @param moduleSetting data
     */
    @ApiOperation(value = "设置企业模块")
    @PostMapping("/setModuleSetting")
    @OperateLog(apply = ApplyEnum.SYSTEM_SETTING, object = OperateObjectEnum.APPLICATION_MANAGEMENT, type = OperateTypeEnum.SETTING)
    public Result setModuleSetting(@Valid @RequestBody ModuleSettingBO moduleSetting) {
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject("应用管理");
        AdminConfig adminConfig = adminConfigService.getById(moduleSetting.getSettingId());
        if (AdminModuleEnum.CRM.getValue().equals(adminConfig.getName())) {
            return Result.error(AdminCodeEnum.ADMIN_MODULE_CLOSE_ERROR);
        }
        adminConfig.setStatus(moduleSetting.getStatus());

        if (ObjectUtil.equal(moduleSetting.getStatus(), 1)) {
            operationLog.setBehavior(BehaviorEnum.START);
        } else {
            operationLog.setBehavior(BehaviorEnum.STOP);
        }
        operationLog.setOperationInfo(operationLog.getBehavior().getName() + adminConfig.getDescription());
        adminConfigService.setModuleSetting(adminConfig);
        return OperationResult.ok(ListUtil.toList(operationLog));
    }

    @ApiOperation(value = "设置日志欢迎语")
    @PostMapping("/setLogWelcomeSpeech")
    public Result setLogWelcomeSpeech(@Valid @RequestBody List<String> stringList) {
        adminConfigService.setLogWelcomeSpeech(stringList);
        return Result.ok();
    }

    /**
     * 获取日志欢迎语列表
     */
    @ApiOperation(value = "获取日志欢迎语")
    @PostMapping("/getLogWelcomeSpeechList")
    public Result<List<LogWelcomeSpeechBO>> getLogWelcomeSpeechList() {
        List<LogWelcomeSpeechBO> adminConfigs = adminConfigService.getLogWelcomeSpeechList();
        return Result.ok(adminConfigs);
    }



    @ApiOperation(value = "设置系统配置")
    @PostMapping("/setAdminConfig/{name}")
    @OperateLog(type = OperateTypeEnum.SETTING, behavior = BehaviorEnum.UPDATE)
    public Result setAdminConfig(@PathVariable("name") String name, @Valid @RequestBody List<AdminConfigBO> list) {
        OperationLog operationLog = adminConfigService.setAdminConfig(name, list);
        return OperationResult.ok(ListUtil.toList(operationLog));
    }

    /**
     * 获取系统配置
     */
    @ApiOperation(value = "获取系统配置")
    @PostMapping("/getAdminConfig/{name}")
    public Result<List<AdminConfigBO>> getAdminConfig(@PathVariable("name") String name) {
        List<AdminConfigBO> adminConfigs = adminConfigService.getAdminConfig(name);
        return Result.ok(adminConfigs);
    }

    /**
     * 删除配置数据
     */
    @ApiOperation(value = "删除配置数据")
    @PostMapping("/deleteConfigById")
    public Result deleteConfigById(@RequestBody @ApiParam(name = "settingId", value = "主键ID", required = true) Integer settingId) {
        if (settingId == null) {
            return Result.error(AdminCodeEnum.ADMIN_DATA_EXIST_ERROR);
        }
        adminConfigService.removeById(settingId);
        return Result.ok();
    }

    /**
     * 查询呼叫中心设置
     */
    @ApiOperation(value = "查询手机端模块设置")
    @PostMapping("/queryCallModuleSetting")
    public Result<ModuleSettingVO> queryCallModuleSetting() {
        ModuleSettingVO moduleSettingVO = adminConfigService.queryCallModuleSetting();
        return Result.ok(moduleSettingVO);
    }

    @ApiOperation(value = "查询自定义配置")
    @PostMapping("/queryCustomSetting/{customKey}")
    public Result<JSONArray> queryCustomSetting(@PathVariable("customKey") String customKey) {
        AdminUserConfig userConfig = adminUserConfigService.queryUserConfigByName(customKey);
        if (userConfig == null) {
            return Result.ok(new JSONArray());
        }
        return Result.ok(JSON.parseArray(userConfig.getValue()));
    }

    /**
     * 修改手机端模块设置
     */

    @ApiOperation(value = "修改自定义配置")
    @PostMapping("/setCustomSetting/{customKey}")
    public Result queryCustomSetting(@RequestBody JSONArray json, @PathVariable("customKey") String customKey) {
        AdminUserConfig userConfig = adminUserConfigService.queryUserConfigByName(customKey);
        if (userConfig != null) {
            userConfig.setValue(json.toJSONString());
            adminUserConfigService.updateById(userConfig);
        } else {
            userConfig = new AdminUserConfig();
            userConfig.setStatus(1);
            userConfig.setName(customKey);
            userConfig.setValue(json.toJSONString());
            userConfig.setUserId(UserUtil.getUserId());
            userConfig.setDescription("用户自定义参数设置");
            adminUserConfigService.save(userConfig);
        }
        return Result.ok();
    }

    @ApiOperation(value = "设置跟进记录常用语")
    @PostMapping("/setActivityPhrase")
    public Result setActivityPhrase(@RequestBody List<String> stringList) {
        String name = "ActivityPhrase";
        Long userId = UserUtil.getUserId();
        String description = "跟进记录常用语";
        adminUserConfigService.deleteUserConfigByName(name);
        List<AdminUserConfig> adminUserConfigList = new ArrayList<>(stringList.size());
        stringList.forEach(str -> {
            AdminUserConfig userConfig = new AdminUserConfig();
            userConfig.setStatus(1);
            userConfig.setName(name);
            userConfig.setValue(str);
            userConfig.setUserId(userId);
            userConfig.setDescription(description);
            adminUserConfigList.add(userConfig);
        });
        adminUserConfigService.saveBatch(adminUserConfigList, Const.BATCH_SAVE_SIZE);
        return Result.ok();
    }

    @ApiOperation(value = "设置scrm的跟进记录常用语")
    @PostMapping("/setScrmActivityPhrase")
    public Result setScrmActivityPhrase(@RequestBody List<String> stringList) {
        String name = "scrmActivityPhrase";
        Long userId = UserUtil.getUserId();
        String description = "scrm跟进记录常用语";
        adminUserConfigService.deleteUserConfigByName(name);
        List<AdminUserConfig> adminUserConfigList = new ArrayList<>(stringList.size());
        stringList.forEach(str -> {
            AdminUserConfig userConfig = new AdminUserConfig();
            userConfig.setStatus(1);
            userConfig.setName(name);
            userConfig.setValue(str);
            userConfig.setUserId(userId);
            userConfig.setDescription(description);
            adminUserConfigList.add(userConfig);
        });
        adminUserConfigService.saveBatch(adminUserConfigList, Const.BATCH_SAVE_SIZE);
        return Result.ok();
    }

    /**
     * 查询跟进记录常用语
     */
    @ApiOperation(value = "查询跟进记录常用语")
    @PostMapping("/queryActivityPhrase")
    public Result<List<String>> queryActivityPhrase() {
        String name = "ActivityPhrase";
        List<AdminUserConfig> adminConfigList = adminUserConfigService.queryUserConfigListByName(name);
        return Result.ok(adminConfigList.stream().map(AdminUserConfig::getValue).collect(Collectors.toList()));
    }

    /**
     * 查询跟进记录常用语
     */
    @ApiOperation(value = "查询scrm跟进记录常用语")
    @PostMapping("/queryScrmActivityPhrase")
    public Result<List<String>> queryScrmActivityPhrase() {
        String name = "scrmActivityPhrase";
        List<AdminUserConfig> adminConfigList = adminUserConfigService.queryUserConfigListByName(name);
        return Result.ok(adminConfigList.stream().map(AdminUserConfig::getValue).collect(Collectors.toList()));
    }

    @ApiExplain(value = "查询config配置")
    @RequestMapping("/queryConfigByName")
    public Result<List<com.kakarote.core.feign.admin.entity.AdminConfig>> queryConfigByName(@RequestParam("name") String name) {
        List<AdminConfig> adminConfigs = adminConfigService.queryConfigListByName(name);
        return Result.ok(adminConfigs.stream().map(config -> BeanUtil.copyProperties(config, com.kakarote.core.feign.admin.entity.AdminConfig.class)).collect(Collectors.toList()));
    }

    @ApiExplain(value = "查询config配置")
    @RequestMapping("/queryFirstConfigByName")
    public Result<com.kakarote.core.feign.admin.entity.AdminConfig> queryFirstConfigByName(@RequestParam("name") String name, HttpServletRequest request) {
        AdminConfig config = adminConfigService.queryConfigByName(name);
        return Result.ok(BeanUtil.copyProperties(config, com.kakarote.core.feign.admin.entity.AdminConfig.class));
    }

    @ApiExplain(value = "通过名字和公司查询config配置")
    @RequestMapping(value = "/queryConfigByNameAndCompanyId")
    public Result<com.kakarote.core.feign.admin.entity.AdminConfig> queryConfigByNameAndCompanyId(@RequestParam("name") String name) {
        AdminConfig config = adminConfigService.queryConfigByNameAndCompanyId(name);
        return Result.ok(BeanUtil.copyProperties(config, com.kakarote.core.feign.admin.entity.AdminConfig.class));
    }

    @ApiExplain(value = "修改config配置")
    @PostMapping("/updateAdminConfig")
    public Result updateAdminConfig(@RequestBody AdminConfig adminConfig) {
        adminConfigService.updateAdminConfig(adminConfig);
        return Result.ok();
    }

    /**
     * 查询跟进记录常用语
     */
    @ApiOperation(value = "验证密码")
    @PostMapping("/verifyPassword")
    public Result<String> verifyPassword(@RequestBody AdminInitDataBO adminInitDataBO) {
        return Result.ok(adminConfigService.verifyPassword(adminInitDataBO));
    }


    /**
     * 查询跟进记录常用语
     */
    @ApiOperation(value = "模块初始化")
    @PostMapping("/moduleInitData")
    @OperateLog(apply = ApplyEnum.SYSTEM_SETTING, object = OperateObjectEnum.INIT_DATA, type = OperateTypeEnum.SETTING, behavior = BehaviorEnum.INIT)
    public Result<Boolean> moduleInitData(@RequestBody AdminInitDataBO adminInitDataBO) {
        List<OperationLog> operationLogList = adminConfigService.moduleInitData(adminInitDataBO);
        return OperationResult.ok(operationLogList);
    }

    @PostMapping("/readNotice")
    @ApiOperation("设置更新日志为已读")
    public Result readNotice() {
        Long userId = UserUtil.getUserId();
        boolean exists = adminUserConfigService.lambdaQuery().eq(AdminUserConfig::getUserId, userId).eq(AdminUserConfig::getName, AdminConst.READ_NOTICE_KEY).exists();
        if (exists) {
            adminUserConfigService.lambdaUpdate().set(AdminUserConfig::getStatus, 1).eq(AdminUserConfig::getUserId, userId).eq(AdminUserConfig::getName, AdminConst.READ_NOTICE_KEY).update();
        } else {
            AdminUserConfig adminUserConfig = new AdminUserConfig();
            adminUserConfig.setValue("");
            adminUserConfig.setName(AdminConst.READ_NOTICE_KEY);
            adminUserConfig.setUserId(userId);
            adminUserConfig.setStatus(1);
            adminUserConfig.setDescription("升级日志阅读状态");
            adminUserConfigService.save(adminUserConfig);
        }
        return Result.ok();
    }

    @PostMapping("/queryReadNoticeStatus")
    @ApiOperation("查询更新日志阅读状态")
    public Result<Boolean> queryReadNoticeStatus() {
        AdminUserConfig userConfig = adminUserConfigService.queryUserConfigByName(AdminConst.READ_NOTICE_KEY);
        boolean isRead = userConfig != null && Objects.equals(1, userConfig.getStatus());
        return Result.ok(isRead);
    }


    @RequestMapping(value = "/updateAdminApplyNumberInfo")
    public Result<Integer> updateAdminApplyNumberInfo(@RequestParam("name") String name, @RequestParam("number") Integer number) {
        Integer info = adminConfigService.updateAdminApplyNumberInfo(name, number);
        return Result.ok(info);
    }

    @PostMapping("/querySimpleEntity")
    @ApiExplain("查询简单的module对象")
    public Result<List<SimpleCrmEntity>> queryModuleInfo(@RequestBody List<Object> ids) {
        List<SimpleCrmEntity> crmEntities = adminConfigService.querySimpleEntity(ids);
        return Result.ok(crmEntities);
    }

    @PostMapping("/queryModulePageList")
    @ApiOperation("查询列表页数据")
    public Result<BasePage<AdminConfig>> queryModulePageList(@RequestBody PageEntity search) {
        search.setPageType(1);
        return Result.ok(adminConfigService.queryModulePageList(search));
    }


}

